package com.whz.generic;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

/**
 * 汉语拼音辅助类
 *
 * @author whz
 */
@Slf4j
@UtilityClass
public class PinYinUtils {

    public static final String HANYU_PATTERN = "[\\u4E00-\\u9FA5]+";

    private static final HanyuPinyinOutputFormat DEFAULT_FORMAT = new HanyuPinyinOutputFormat();
    private static final Pattern COMPILE = Pattern.compile(HANYU_PATTERN);
    private static final Pattern COMPILED = Pattern.compile(HANYU_PATTERN);

    static {
        DEFAULT_FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        DEFAULT_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        DEFAULT_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
    }

    /**
     * 返回汉字的拼音
     *
     * @param src 汉字
     * @return 拼音
     */
    @SneakyThrows
    public static String getPingYin(final String src) {
        if (StringUtils.isEmpty(src)) {
            return src;
        }
        StringBuilder pinyin = new StringBuilder();
        for (final char c : src.toCharArray()) {
            if (COMPILE.matcher(Character.toString(c)).matches()) {
                String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, DEFAULT_FORMAT);
                pinyin.append(temp[0]);
            } else {
                pinyin.append(c);
            }
        }
        return pinyin.toString();
    }

    /**
     * 获取汉字首字母
     *
     * @param src 汉字
     * @return 首字母
     */
    @SneakyThrows
    public static String getPinYinHeadChar(final String src) {
        if (StringUtils.isEmpty(src)) {
            return src;
        }
        StringBuilder convert = new StringBuilder();
        for (final char word : src.toCharArray()) {
            if (COMPILED.matcher(Character.toString(word)).matches()) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, DEFAULT_FORMAT);
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        return convert.toString();
    }
}